﻿using System;
using biz.ritter.javapi.io;
using biz.ritter.javapi.lang;
using biz.ritter.javapi.net;
using Nofs.Net.Fuse.Impl;

namespace Nofs.Net.Execution
{
    public class ExecutionServerDriver : Thread
    {
        private Socket _socket;
        private PathTranslator _translator;
        private LogManager _logger;

        public ExecutionServerDriver(
                Socket socket,
                PathTranslator translator,
                LogManager logger)
        {
            _socket = socket;
            _translator = translator;
            _logger = logger;
        }

        //@Override
        public override void run()
        {
            try
            {
                _logger.LogInfo("Reading packet...");
                StringBuffer buffer = new StringBuffer();
                InputStream input = _socket.getInputStream();
                int data;
                while ((data = input.read()) != (-1))
                {
                    char chr = (char)data;
                    buffer.append(chr);
                    //_logger.LogInfo("Buffer: " + buffer.toString());
                    if (buffer.lastIndexOf("</MethodInvocation>") != (-1))
                    {
                        break;
                    }
                }
                _logger.LogInfo("Finished reading packet.");
                int result = new ExecutionServerHandler(_translator, _logger).Handle(buffer.toString());
                _socket.getOutputStream().write(result);
                _socket.close();
            }
            catch (System.Exception e)
            {
                //e.printStackTrace();
                _logger.LogError(e.getMessage());
            }
        }
    }

}
